[英]How to change the background color of a view from a different activity in android?
我正在開發一個測驗應用程序。 First when a user opens the app they go to the MainActivity
, from there when they press start they go to the Categories Activity, from there after selecting a category they go to the Sets Activity, from there after selecting a set the go to the Questions活動,最后在完成所有問題后,他們到達分數活動。 在得分活動中,當單擊完成按鈕時,它們將被重定向到MainActivity
。 在得分活動中,我想將他們完成的 Set 的顏色更改為綠色而不是默認顏色。 我怎樣才能做到這一點? 我創建了一個集合項目布局 xml 文件,並使用適配器在 Sets Activity 中使用來自適配器的視圖填充gridview
。 目前,單擊 ScoreActivity 中的“完成”按鈕后,我得到了 null object 參考。
這是代碼:
SetsAdapter.java
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
@Override
public int getCount() {
return numOfSets;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view;
if(convertView == null){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
}
else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent questionIntent = new Intent(parent.getContext(), QuestionActivity.class);
questionIntent.putExtra("SETNUM", position +1);
parent.getContext().startActivity(questionIntent);
}
});
((TextView) view.findViewById(R.id.setNumber)).setText(String.valueOf(position+1));
return view;
}
}
SetsActivity.java
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
private FirebaseFirestore firestore;
public static int categoryID;
private Dialog loadingDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
Toolbar toolbar = (Toolbar)findViewById(R.id.set_toolbar);
setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
categoryID = getIntent().getIntExtra("CATEGORY_ID",1);
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridView);
loadingDialog = new Dialog(SetsActivity.this);
loadingDialog.setContentView(R.layout.loading_progressbar);
loadingDialog.setCancelable(false);
loadingDialog.getWindow().setBackgroundDrawableResource(R.drawable.progress_background);
loadingDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
loadingDialog.show();
firestore = FirebaseFirestore.getInstance();
loadSets();
}
private void loadSets() {
firestore.collection("Quiz").document("CAT" + String.valueOf(categoryID))
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc.exists()) {
long sets = (long) doc.get("SETS");
SetsAdapter adapter = new SetsAdapter(Integer.valueOf((int)sets));
sets_grid.setAdapter(adapter);
} else {
Toast.makeText(SetsActivity.this, "No Sets Exists!", Toast.LENGTH_SHORT).show();
finish();
}
} else {
Toast.makeText(SetsActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
loadingDialog.cancel();
}
});
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
ScoreActivity.java
public class ScoreActivity extends AppCompatActivity {
private TextView score;
private Button done;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
score = findViewById(R.id.score_tv);
done = findViewById(R.id.score_activity_done);
String score_str = getIntent().getStringExtra("SCORE");
final int setNum = getIntent().getIntExtra("SetNum", 1);
score.setText(score_str);
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Here is the issue I am facing
View view = findViewById(R.id.setNumber);
view.setBackgroundColor(Color.GREEN);
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
}
}
由於您的活動序列是MainActivity
-> Categories
-> Sets
-> Scores
。
您有兩個選項來更改顏色,具有兩個不同的生命周期的更改。
要臨時更改顏色,這將在關閉應用程序或重新啟動“Sets”活動后自行重置。 可以通過兩種方式完成:使用公共 Static 變量和使用公共 function。
永久更改顏色,直到應用程序被卸載/重新安裝。 您應該使用SharedPreferences
。 SharedPreferences
就像存儲在設備的 memory 中以供進一步使用的私有數據一樣,並且除非應用程序被刪除/數據被清除,否則它會保持不變。 雖然,具有 root 權限的應用程序可以訪問任何應用程序的SharedPreferences
數據,也可以對其進行修改。
您可以按照此處的說明使用SharedPreferences
。 或者,您可以使用一些庫以一種簡單的方式訪問它。 我在所有應用程序中使用它的方式是TinyDB (它只是一個 java/kotlin 文件)。 這可以作為:
//store the value from ScoreActivity after completion as TinyDB tinyDB = TinyDB(this); tinyDB.putBoolean("isSet1Completed",true); //access the boolean variable in SetsActivity to change the color of any set that //is completed and if it's true, just change the color. TinyDB tinyDB = TinyDB(this); Boolean bool1 = tinyDB.getBoolean("isSet1Completed");
但是,您喜歡哪種方式是您的選擇。 現在,這是關於您將要進行的更改的生命周期:臨時或永久。 現在,我們將討論如何更改顏色。
在Sets
活動中使用公共 static 變量。 您可以做的是您可以將要更改其背景的 imageView/textview 設置為公共 static 變量。 請記住,這個想法不是首選,因為它會導致 memory 泄漏,但這很容易。
將其聲明為public static ImageView imageview;
(或TextView
)在onCreated()
中將其初始化為imageView = finViewById(R.id.viewId);
在Sets
活動中。
將其稱為new SetsActivity().imageView.setBackgroundColor(yourColor);
在ScoreActivity
中。
第二種方法是在 SetsAcitvity 中創建一個公共的SetsAcitvity
,將顏色更改代碼放入其中,然后從ScoreActivity
中調用它。 只需將其聲明為public void changeColor(){ //your work}
並從ScoreActivity
其稱為new SetsActivity().changeCOlor()
。 您還可以像setId
一樣將一些 arguments 傳遞給 function 。
我已經為你提供了你需要的一切。 Rest 你應該弄清楚自己要真正學習它而不是復制它。
我認為您只需在 MainActivity 中添加標志。
例如,在 MainActivity 中添加標志。
boolean isFromDone = false;
完成點擊后,
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Here is the issue I am facing
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
mainIntent.putExtra("FromDone", true);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
在 MainActivity 中添加這個。
@Override
protected void onResume() {
super.onResume();
isFromDone = getIntent().getBooleanExtra("FromDone", false);
if(isFromDone) {
(TextView) view.findViewById(R.id.setNumber)).setBackgroundColor(Color.GREEN);
}
}
假設您在活動 A 中有一個線性布局,並且您想通過單擊活動 B 中的按鈕來更改它的背景顏色。
Step 1
創建 class 並聲明 static 變量。
class Util { private static LinearLayout mylayout ; }
Step 2
在持有此布局的活動中,對其進行初始化。
Util.mylayout = findviewbyid(R.id.linear);
Step 3
從活動 B 更改按鈕單擊的背景顏色
onClick{
Util.mylayout.setBackgroundColor(Color.RED);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.