-1
我有一個佈局,我想用菜單充氣。問題是這並沒有擴大到它。基本上我嘗試了很多方法,這只是找到的方法。菜單的充氣菜單佈局不起作用
public class PostDetailActivity extends AppCompatActivity implements View.OnClickListener {
public static final String EXTRA_POST_KEY = "post_key";
private static final String TAG = "PostDetailActivity";
private static ProgressDialog progress;
private DatabaseReference mPostReference;
private DatabaseReference mCommentsReference;
private ValueEventListener mPostListener;
private String mPostKey;
private CommentAdapter mAdapter;
private TextView numStarsView;
private TextView mAuthorView;
private TextView mAuthorEmailView;
private ImageView mAuthorPhotoView;
private TextView mTitleView;
private TextView mBodyView;
private EditText mCommentField;
private Button mCommentButton;
private RecyclerView mCommentsRecycler;
private TextView mStreamView;
private TextView mSubjectView;
private LinearLayoutManager mCommentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_detail);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//progress bar for network check
SpannableStringBuilder loadingText = new SpannableStringBuilder();
loadingText.append("Server not reachable.Check internet Connection");
loadingText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
loadingText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
progress = new ProgressDialog(this);
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.setMessage(loadingText);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// Get post key from intent
mPostKey = getIntent().getStringExtra(EXTRA_POST_KEY);
if (mPostKey == null) {
throw new IllegalArgumentException("Must pass EXTRA_POST_KEY");
}
// Initialize Database
mPostReference = FirebaseDatabase.getInstance().getReference()
.child("posts").child(mPostKey);
mCommentsReference = FirebaseDatabase.getInstance().getReference()
.child("post-comments").child(mPostKey);
// Initialize Views
mAuthorView = (TextView) findViewById(R.id.post_author);
mAuthorEmailView = (TextView) findViewById(R.id.post_email);
mAuthorPhotoView = (ImageView) findViewById(R.id.post_author_photo);
mTitleView = (TextView) findViewById(R.id.post_title);
mBodyView = (TextView) findViewById(R.id.post_body);
numStarsView = (TextView) findViewById(R.id.post_num_stars_cmnt);
mStreamView = (TextView) findViewById(R.id.post_stream);
mSubjectView = (TextView) findViewById(R.id.post_subject);
mCommentField = (EditText) findViewById(R.id.field_comment_text);
mCommentButton = (Button) findViewById(R.id.button_post_comment);
mCommentsRecycler = (RecyclerView) findViewById(R.id.recycler_comments);
mCommentsRecycler.setNestedScrollingEnabled(false);
mCommentButton.setOnClickListener(this);
mCommentManager = new LinearLayoutManager(this);
mCommentManager.setReverseLayout(true);
mCommentManager.setStackFromEnd(true);
mCommentsRecycler.setLayoutManager(mCommentManager);
isOnlne();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.new_comment_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.inflating_comment_menu:
// TODO update alert menu icon
Toast.makeText(this, "update clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onStart() {
super.onStart();
isOnlne();
// Add value event listener to the post
// [START post_value_event_listener]
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Post post = dataSnapshot.getValue(Post.class);
// [START_EXCLUDE]
mAuthorView.setText(post.author);
mAuthorEmailView.setText(post.authorEmail);
mTitleView.setText(post.title);
mBodyView.setText(post.body);
mStreamView.setText(post.stream);
mSubjectView.setText(post.subject);
if (post.userImage.equalsIgnoreCase("phone")) {
mAuthorPhotoView.setImageResource(R.drawable.blue_call_icon);
mAuthorEmailView.setVisibility(View.INVISIBLE);
} else {
mAuthorEmailView.setVisibility(View.VISIBLE);
Picasso.with(PostDetailActivity.this).load(post.userImage)
.placeholder(R.drawable.google)
.error(R.drawable.ic_action_account_circle_40)
.into(mAuthorPhotoView);
}
// [END_EXCLUDE]
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// [START_EXCLUDE]
SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Failed to load comments,reload post");
snackbarText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Snackbar bar = Snackbar.make(findViewById(R.id.button_post_comment), snackbarText
, Snackbar.LENGTH_SHORT);
View sbView = bar.getView();
sbView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),
R.color.pure_red));
bar.show();
// [END_EXCLUDE]
}
};
mPostReference.addValueEventListener(postListener);
// [END post_value_event_listener]
// Keep copy of post listener so we can remove it when app stops
mPostListener = postListener;
// Listen for comments
mAdapter = new CommentAdapter(this, mCommentsReference);
mCommentsRecycler.setAdapter(mAdapter);
}
@Override
public void onStop() {
super.onStop();
// Remove post value event listener
if (mPostListener != null) {
mPostReference.removeEventListener(mPostListener);
}
// Clean up comments listener
mAdapter.cleanupListener();
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.button_post_comment) {
postComment();
}
}
public String getUid() {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
if (uid == null) {
Intent intent = new Intent(getApplicationContext(), Login.class);
startActivity(intent);
}
return uid;
}
private void postComment() {
final String uid = getUid();
final String userImage;
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String userEmail = currentUser.getEmail().toString();
if ((userEmail != null) && (userEmail != "") && (userEmail.contains("@"))) {
userImage = currentUser.getPhotoUrl().toString();
} else {
userImage = "phone";
}
FirebaseDatabase.getInstance().getReference().child("users").child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
User user = dataSnapshot.getValue(User.class);
String authorName = user.username + " (" + user.email + ")";
// Create new comment object
String commentText = mCommentField.getText().toString();
if (TextUtils.isEmpty(commentText)) {
mCommentField.setError("comment shouldn't empty");
return;
}
isOnlne();
Comment comment = new Comment(uid, authorName, commentText, userImage);
// Push the comment, it will appear in the list
mCommentsReference.push().setValue(comment);
SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Your comment has been added");
snackbarText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Snackbar bar = Snackbar.make(findViewById(R.id.button_post_comment), snackbarText,
Snackbar.LENGTH_SHORT);
View sbView = bar.getView();
sbView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),
R.color.colorPrimary));
bar.show();
// Clear the field
mCommentField.setText(null);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void isOnlne() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
changeStatus(true);
} else {
changeStatus(false);
}
}
// Method to change the text status
public void changeStatus(boolean isConnected) {
// Change status according to boolean value
if (isConnected) {
progress.dismiss();
} else {
progress.show();
}
}
@Override
protected void onPause() {
super.onPause();
NetworkCheker.activityPaused();// On Pause notify the Application
}
@Override
protected void onResume() {
super.onResume();
NetworkCheker.activityResumed();// On Resume notify the Application
}
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
@Override
public void onBackPressed() {
super.onBackPressed();
onSupportNavigateUp();
}
private static class CommentViewHolder extends RecyclerView.ViewHolder {
public TextView authorView;
public TextView bodyView;
public ImageView authorPhotoView;
private Button commentDelete;
public CommentViewHolder(final View itemView) {
super(itemView);
authorPhotoView = (ImageView) itemView.findViewById(R.id.comment_photo);
authorView = (TextView) itemView.findViewById(R.id.comment_author);
bodyView = (TextView) itemView.findViewById(R.id.comment_body);
commentDelete = (Button) itemView.findViewById(R.id.comment_delete);
}
}
private class CommentAdapter extends RecyclerView.Adapter<CommentViewHolder> {
private Context mContext;
private DatabaseReference mDatabaseReference;
private ChildEventListener mChildEventListener;
private List<String> mCommentIds = new ArrayList<>();
private List<Comment> mComments = new ArrayList<>();
public CommentAdapter(final Context context, DatabaseReference ref) {
mContext = context;
mDatabaseReference = ref;
// Create child event listener
// [START child_event_listener_recycler]
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
Comment comment = dataSnapshot.getValue(Comment.class);
// [START_EXCLUDE]
// Update RecyclerView
mCommentIds.add(dataSnapshot.getKey());
mComments.add(comment);
notifyItemInserted(mComments.size() - 1);
mCommentManager.scrollToPosition(mComments.size() - 1);
// [END_EXCLUDE]
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
Comment newComment = dataSnapshot.getValue(Comment.class);
String commentKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int commentIndex = mCommentIds.indexOf(commentKey);
if (commentIndex > -1) {
// Replace with the new data
mComments.set(commentIndex, newComment);
// Update the RecyclerView
notifyItemChanged(commentIndex);
mCommentManager.scrollToPosition(commentIndex);
} else {
Log.w(TAG, "onChildChanged:unknown_child:" + commentKey);
}
// [END_EXCLUDE]
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
String commentKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int commentIndex = mCommentIds.indexOf(commentKey);
if (commentIndex > -1) {
// Remove data from the list
mCommentIds.remove(commentIndex);
mComments.remove(commentIndex);
SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Comment has been removed");
snackbarText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Snackbar bar = Snackbar.make(findViewById(R.id.button_post_comment), snackbarText
, Snackbar.LENGTH_SHORT);
View sbView = bar.getView();
sbView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),
R.color.pure_red));
bar.show();
// Update the RecyclerView
notifyItemRemoved(commentIndex);
mCommentManager.scrollToPosition(commentIndex);
} else {
Log.w(TAG, "onChildRemoved:unknown_child:" + commentKey);
}
// [END_EXCLUDE]
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
Comment movedComment = dataSnapshot.getValue(Comment.class);
String commentKey = dataSnapshot.getKey();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Failed to load comments.");
snackbarText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Snackbar bar = Snackbar.make(findViewById(R.id.button_post_comment),
snackbarText, Snackbar.LENGTH_SHORT);
View sbView = bar.getView();
sbView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),
R.color.pure_red));
}
};
ref.addChildEventListener(childEventListener);
// [END child_event_listener_recycler]
// Store reference to listener so it can be removed on app stop
mChildEventListener = childEventListener;
}
@Override
public CommentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.item_comment, parent, false);
return new CommentViewHolder(view);
}
@Override
public void onBindViewHolder(final CommentViewHolder holder, final int position) {
final Comment comment = mComments.get(position);
final String commentKey = mCommentIds.get(position);
holder.authorView.setText(comment.author);
holder.bodyView.setText(comment.text);
if (comment.userImage.equalsIgnoreCase("phone")) {
holder.authorPhotoView.setImageResource(R.drawable.blue_call_icon);
} else {
Picasso.with(mContext).load(comment.userImage)
.placeholder(R.drawable.google)
.error(R.drawable.ic_action_account_circle_40)
.into(holder.authorPhotoView);
}
if (comment.uid.matches(getUid())) {
holder.commentDelete.setVisibility(View.VISIBLE);
} else {
holder.commentDelete.setVisibility(View.GONE);
}
holder.commentDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(PostDetailActivity.this);
builder.setMessage("Are you sure you want to delete this comment?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mCommentsReference.child(commentKey).getRef().removeValue();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
@Override
public int getItemCount() {
numStarsView.setText(String.valueOf(mComments.size()));
return mComments.size();
}
public void cleanupListener() {
if (mChildEventListener != null) {
mDatabaseReference.removeEventListener(mChildEventListener);
}
}
}}
代碼,我是充氣
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/inflating_comment_menu"
android:actionLayout="@layout/new_comment_menu"
android:title=""
app:showAsAction="always" />
</menu>
是在動作設計上使用
和佈局是
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="@+id/post_author_layout_inflate"
layout="@layout/include_post_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<LinearLayout
android:id="@+id/star_layout_inflate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/post_author_layout"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/post_author_layout"
android:layout_marginRight="10dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="@+id/star_cmnt_inflate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:background="?attr/selectableItemBackground"
android:src="@drawable/ic_create_black_24dp" />
<TextView
android:id="@+id/post_num_stars_cmnt_inflate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#000"
android:textStyle="bold"
tools:text="7" />
</LinearLayout>
</RelativeLayout>
感謝@Adolfo其工作但正如你看到的,我有我的自定義XML的TextView與ImageView的一起卻只有ImageView的是出現在動作欄中沒有的TextView在應用 –
@UttamMeerwal也許它因爲看到您在自定義視圖「inflating_comment_menu」的框架佈局中使用了wrap_content,請嘗試使用固定尺寸。 –