我不知道为什么这段代码不起作用。我有TextView
名为text1
和Button
名为button1
。我想点击text1
后更改button1
中的文字。
我注意到程序在我评论第button1.setOnClickListener(this);
行时有效,但结果没有发生。
package com.example.testowaniefragmentow;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements OnClickListener {
TextView text1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button_B1);
button1.setOnClickListener(this);
TextView text1 = (TextView) findViewById(R.id.textview_text);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,false);
return rootView;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_B1:
text1.setText("Text has been changed");
break;
default:
break;
}
}
}
答案 0 :(得分:2)
更改
setContentView(R.layout.activity_main);
到
setContentView(R.layout.fragment_main);
希望有所帮助......
或强>
正如迈克所说,将fragment_main.xml
的全部内容复制到activity_main.xml
..
答案 1 :(得分:0)
您错误地定义了TextView。您的代码中有两个文本TextView。一个在MainActivity类中,第二个是onCreate方法的局部变量。所以在你的onClicklistener中,当你尝试为text1设置文本时,它实际上没有被初始化。请在MainActivity类和onCreate方法中更改您的代码,如下所示,并保持一致。
//declare the view and button here.
TextView text1;
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialise the view and button here but do not declare it again or else they will become local variable
button1 = (Button) findViewById(R.id.button_B1);
button1.setOnClickListener(this);
text1 = (TextView) findViewById(R.id.textview_text);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
答案 2 :(得分:0)
试试这个兄弟:
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button_B1:
text1.setText("Text has been changed");
break;
default:
break;
}
}
});