activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity" >
<fragment
android:id="@+id/fragment1"
android:name="sithi.test.fragmenttest.Fragment1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
片段1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="btnClick1" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
ActivityMain.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
片段1.java
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class Fragment1 extends Fragment
{
TextView tv;
@Override
public void onStart()
{
// TODO Auto-generated method stub
super.onStart();
tv=(TextView)getView().findViewById(R.id.textView1);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
// TODO Auto-generated method stub
//inflater.inflate(resource, root, attachToRoot);
return inflater.inflate(R.layout.fragment1, container, false);
}
public void btnClick1(View view)
{
tv.setText("dsdsdasda");
}
}
我创建了这样的 xml 文件和类,但btnClick1()
在 Android Fragment 中不起作用。当我单击片段中的该按钮时,它将出现错误。我已经在 Fragment 类中编写了该按钮单击功能。