按钮单击Android的碎片不工作 [英] Button click in Android Fragment does not work

查看:188
本文介绍了按钮单击Android的碎片不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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>

fragment1.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;
}

}

Fragment1.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的碎片的工作。 它会得到一个错误,当我点击的片段按钮。我写了按钮,点击功能片段类中。

I created xml files and classes like this but btnClick1() does not work in Android Fragment. It will getting an error when i clicking that button in the fragment. I have written that button click function inside the Fragment class.

推荐答案

您需要分配OnClickListener的片段code,使其工作。见Snicolas回答的为什么。

You need to assign OnClickListener in fragment code to make it work. See Snicolas answer for the "why".

这篇关于按钮单击Android的碎片不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆