我正在學習Android並堅持這一點。 我想在Android中製作一個項目。在MainActivity中,我有一個按鈕,並希望設置onClick()事件,如果按鈕的文本是「SOLVE」,然後添加片段輸出並將按鈕的名稱更改爲「BACK」,並且如果按鈕的文本是「BACK」,則添加片段Input並將Button的文本更改爲「SOLVE」。如何更改Android中的片段
這裏是我的MainActivity.java代碼
package com.example.sudokusolver;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button a
String check ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a=(Button) findViewById(R.id.press);
check=a.getText().toString();
a.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if(check.equals("SOLVE")){
Output OP=new Output();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft =
fragmentManager.beginTransaction();
ft.add(R.id.frag,OP);
ft.commit();
a.setText("BACK");
}
else
{
Input IP=new Input();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft =
fragmentManager.beginTransaction();
ft.add(R.id.frag,IP);
ft.commit();
a.setText("SOLVE");
}
}
});
}
}
這裏的main_activit.xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/frag"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="0dp"
/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="90dp">
<Button
android:id="@+id/press"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/show" />
</RelativeLayout>
</LinearLayout>
的問題是(你可能已經看到)我不能比較(檢查字符串)非內部類中的最終變量。所以,請幫助我,如果你認爲我的整個想法是錯誤的,那麼建議我適當的方式。
(如果其他文件需要然後告訴我,我會編輯)
編輯
有什麼毛病我的邏輯。當我第一次按'解決'時,它轉向'後退'。但是當我按下「返回」時,它不會轉向「解決」。我想解決>返回>解決>返回...我錯過了什麼? (可能是增加/替換交易?)
定義全局視圖..不需要處理最終.. – Ranjit 2014-10-12 08:29:53
如果按鈕除此之外沒有其他用途,則不需要聲明它爲final或全局聲明它。只需使用'onClick'中的參數'view'即可。 'view'有'Button'本身 – Panther 2014-10-12 08:33:38
我的邏輯有問題。當我第一次按'解決'時,它轉向'後退'。但是當我按下「返回」時,它不會轉向「解決」。我想解決>返回>解決>返回...我錯過了什麼? (也許在添加/替換交易?) – ajay 2014-10-12 09:09:40