這是我在導航抽屜中使用的片段之一。我需要添加一個按鈕,當按下時,將文本框更改爲不同的文本。我不斷收到findviewbyid()int無法解析的錯誤等。我可以在MainActivity/activity_main上工作,但是當我使用導航抽屜的某個頁面(如ConnectFragment.java/fragment_connect.xml)時,出現錯誤。findviewbyid - 無法解析
這是代碼只是單獨ConnectFragment
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class ConnectFragment extends Fragment {
public ConnectFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_connect, container, false);
return rootView;
}
}
這是我想在這裏從XML實現
final Button ClassAButton = (Button)findViewById(R.id.ClassAButton);
ClassAButton.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View view){
TextView FeloniesText = (TextView)findViewById(R.id.FeloniesText);
FeloniesText.setText("Button 1 Has been pressed!");
}
}
);
代碼(相對佈局標籤的代碼,格式化搞砸了)
http://schemas.android.com/tools「 機器人:layout_width = 「match_parent」 機器人:layout_height = 「match_parent」 機器人:取向= 「垂直」 機器人:背景= 「@顏色/的backgroundColor」>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/ClassAButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/FeloniesText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="107dp" />
</RelativeLayout>
我也希望添加多個按鈕將文本視圖更改爲不同的東西,所以我會喜歡,類A按鈕打印出嗨,B類按鈕打印出來是的,C類按鈕打印出大象,等等。任何幫助將不勝感激。 :D BTW API 15
@TyreseBrown檢查我的編輯答案。 –
感謝您的幫助,代碼正常工作,沒有更多的錯誤,但按下按鈕後,應用程序崩潰,幫助? –
致命例外:main 進程:nota.outlawsindex,PID:3236 java.lang.NullPointerException:嘗試在空對象引用 上調用虛擬方法'void android.widget.TextView.setText(java.lang.CharSequence)'在nota.outlawsindex.ConnectFragment $ 1.onClick(ConnectFragment.java:33) –