我的应用程序中有一个导航抽屉。为了支持它,我必须创建一个自定义操作栏。我想根据片段更改自定义栏的标题。
当我尝试:
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("your title");
我的应用崩溃,logcat没有给我任何适当的错误。请帮助!
MainActivity
package com.app.myapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import com.parse.ParseAnalytics;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import org.w3c.dom.Text;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
EditText editText;
public void setNavBar(){
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
public void update_menu(View view){
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(ParseUser.getCurrentUser() == null){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}else{
setContentView(R.layout.activity_main);
setNavBar();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(MainActivity.this);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
navigationView.setCheckedItem(R.id.broadcast);
}
}
ParseAnalytics.trackAppOpenedInBackground(getIntent());
}
@Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.broadcast:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
break;
case R.id.profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ProfileFragment()).commit();
break;
case R.id.monthlyMenu:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MenuFragment()).commit();
break;
case R.id.logout:
ParseUser.logOut();
Toast.makeText(MainActivity.this, "Logged out", Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent1);
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/cardview_dark_background"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:menu="@menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
广播片段(我创建的唯一片段,我想让我的操作栏显示“广播”):
package com.app.myapp;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toolbar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
class BroadcastAdapter extends ArrayAdapter<String>{
Context context;
ArrayList<String> messages;
List<String> from1;
BroadcastAdapter(Context c, ArrayList<String> message, List<String> from){
super(c, R.layout.broadcast_list, R.id.messageTextView, message);
this.context = c;
this.messages = message;
this.from1 = from;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) getContext().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.broadcast_list, parent, false);
TextView messageTextView = view.findViewById(R.id.messageTextView);
TextView sentByTextView = view.findViewById(R.id.sentByTextView);
messageTextView.setText(messages.get(position));
sentByTextView.setText(from1.get(position));
return super.getView(position, convertView, parent);
}
}
public class HomeFragment extends Fragment {
ArrayList<String> messages;
List<String> sent;
BroadcastAdapter adapter;
private void getMessages() {
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Broadcast");
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null && objects.size() > 0) {
for (ParseObject object : objects) {
Log.i("===========> ", object.getString("message"));
String from = object.getString("from");
Log.i("===========>", from);
sent.add(from);
messages.add(object.getString("message"));
adapter.notifyDataSetChanged();
}
} else {
Log.i("===========> ", "Failed");
}
}
});
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
// Toolbar toolbar = v.findViewById(R.id.toolbar);
// ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("your title");
View rootView = inflater.inflate(R.layout.home_fragment, container, false);
messages = new ArrayList<String>();
sent = new ArrayList<String>();
adapter = new BroadcastAdapter(getActivity().getApplicationContext(), messages, sent);
ListView listView = rootView.findViewById(R.id.broadcastListView);
listView.setAdapter(adapter);
getMessages();
return rootView;
}
}
如果您不将活动投射到AppCompatActivity怎么办?您实际上需要活动的工具栏。