java - 如何在RelativeLayout中固定Textview的位置

标签 java android android-layout android-relativelayout

我遇到这个问题,我想修复布局的位置。我想将其修复在布局的中心,但每次单击 EditText 都会弹出键盘,TextView 就会向上移动,我不希望这样即将发生。这是我的代码:

评论.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:flatui="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:fresco="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" android:fitsSystemWindows="true"
    android:id="@+id/comments_coordinator_layout">

    <android.support.design.widget.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/comments_appbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/layout_comments">

            <LinearLayout
                android:id="@+id/send_message"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="4dp"
                android:layout_alignParentBottom="true"
                android:orientation="horizontal" >

                <com.cengalabs.flatui.views.FlatEditText
                    android:fontFamily="sans-serif"
                    android:id="@+id/write_comment"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="5"
                    android:paddingTop="6dp"
                    android:paddingBottom="6dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:gravity="left"
                    android:textSize="16sp"
                    flatui:fl_theme="@array/color_primary_theme"
                    android:textColor="#000000"
                    android:cursorVisible="false"
                    android:hint="Comment back!"
                    android:background="@color/feed_bg"
                    android:inputType="textMultiLine"
                    flatui:fl_fieldStyle="fl_box"
                    android:scrollHorizontally="false" />

                <com.cengalabs.flatui.views.FlatButton
                    android:fontFamily="sans-serif"
                    android:id="@+id/send_comment"
                    android:layout_width="wrap_content"
                    android:layout_height="fill_parent"
                    android:layout_marginLeft="5dp"
                    android:textSize="16sp"
                    android:padding="5dp"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:text="Send"
                    flatui:fl_theme="@array/color_primary_theme"
                    android:textAllCaps="false"
                    flatui:fl_textAppearance="fl_light"/>
            </LinearLayout>

            <android.support.v7.widget.RecyclerView
                android:scrollbars="vertical"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@id/send_message"
                android:id="@+id/view_comments">
            </android.support.v7.widget.RecyclerView>

            <TextView
                android:id="@+id/no_comments_text"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_horizontal|center_vertical"
                android:visibility="gone"
                android:textSize="16sp"
                android:fontFamily="sans-serif"
                android:text="No comments to display." />
        </RelativeLayout>

</android.support.design.widget.CoordinatorLayout>

评论.java:

public class Comments extends AppCompatActivity {

    Post post;
    private CommentsDataSource commentsDatasource;
    //Local Database for storing posts
    private PostsDataSource postsDataSource;
    private FireBaseApplication application;
    private List<Comment> commentItems;
    private CommentsRecyclerViewAdapter commentsRecyclerViewAdapter;
    private RecyclerView commentsView;
    private TextView noCommentsView;
    private Toolbar toolbar;
    private LinearLayoutManager llm;
    private NotificationManager notificationManager;
    private boolean isNotificationActive;
    private String postId;
    private String tab;
    private String userId;
    private String posterUserId;
    private String posterName;
    private String postTimeStamp;
    private String postStatus;
    //Progress overlay
    View progressOverlay;
    DatabaseQuery databaseQuery;
    String name;

    private Firebase firebaseRef = new Firebase("https://tabsapp.firebaseio.com/");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.comments);
        setupActionBar();
        setupActivity(savedInstanceState);

        final EditText comment = (EditText) findViewById(R.id.write_comment);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        //Once we send the post, we want to
        comment.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                comment.setCursorVisible(false);
                if (event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    comment.setImeOptions(EditorInfo.IME_ACTION_DONE);
                    in.hideSoftInputFromWindow(comment.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return false;
            }
        });

        //Hide the cursor until view is clicked on
        View.OnTouchListener onTouchListener = new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                System.out.println("Touched");
                if (v.getId() == comment.getId()) {
                    comment.setCursorVisible(true);
                }
                commentsView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        commentsView.smoothScrollToPosition(commentsView.getAdapter().getItemCount() - 1);
                    }
                }, 250);
                return false;
            }
        };
        comment.setOnTouchListener(onTouchListener);

        //Button for sending post
        final Button button = (Button) findViewById(R.id.send_comment);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (TextUtils.isEmpty(comment.getText())) {
                    Toast.makeText(Comments.this, "Please enter in a comment first.", Toast.LENGTH_SHORT).show();
                } else {
                    String text = comment.getText().toString();
                    Comment createdComment = new Comment("", postId, name, text, userId, getDateTime());
                    Toast.makeText(Comments.this, "Successfully commented.", Toast.LENGTH_SHORT).show();
                    comment.setText("");
                    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    in.hideSoftInputFromWindow(comment.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    comment.setCursorVisible(false);
                    updatePost();
                    databaseQuery.saveCommentToFirebase(createdComment);
                    saveCommentInCloud(createdComment, tab);
                    if (noCommentsView.getVisibility() == View.VISIBLE) {
                        noCommentsView.setVisibility(View.GONE);
                    }
                    //Notify friends that user has posted a comment on their post. Don't get notification if you posted on your own post.
//                    if(!createdComment.getCommenterUserId().equals(userId)) {
//                        showNotification(v, commenter);
//                    }

                }

            }
        });
        //Now we have to show a loading bar so that we are loading the comments. While we are loading the comments, we update the comments header
        populateCommentView(postId);
    }

    public void populateCommentView(String postId) {
        commentItems = new ArrayList<Comment>();
        getComments(postId);
    }

    private void setupActionBar() {
        toolbar = (Toolbar) findViewById(R.id.comments_appbar);
        setSupportActionBar(toolbar);
        //Back bar enabled
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                //What happens if you click back
                NavUtils.navigateUpFromSameTask(this);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void updatePost(){
        commentsView.postDelayed(new Runnable() {
            @Override
            public void run() {
                commentsView.smoothScrollToPosition(commentsView.getAdapter().getItemCount());
                //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

            }
        }, 1000);
    }

    private void checkAdapterIsEmpty () {
        if(application.getCommentsRecyclerViewAdapter().getItemCount() == 1){
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) noCommentsView.getLayoutParams();
            params.addRule(RelativeLayout.BELOW, R.id.view_post);
            noCommentsView.setVisibility(View.VISIBLE);
        }
        else {
            noCommentsView.setVisibility(View.GONE);
        }
    }

    public CommentsHeader getCommentsHeader(String id)
    {
        System.out.println("Going to inflate header");
        CommentsHeader header = new CommentsHeader();
        header.setPosterUserId(posterUserId);
        header.setPosterName(posterName);
        header.setPosterDate(postTimeStamp);
        header.setViewStatus(postStatus);
        return header;
    }


    public void populatePost(String id) {
        TextView statusMsg = (TextView)findViewById(R.id.view_status);
        System.out.println("Post: " + post);
        statusMsg.setText(post.getStatus());

        //Set profile picture
        DraweeController controller = news_feed.getImage(userId);
        SimpleDraweeView draweeView = (SimpleDraweeView) findViewById(R.id.poster_picture);
        draweeView.setController(controller);

        //Set poster's name
        TextView posterName = (TextView)findViewById(R.id.poster_name);
        posterName.setText(post.getName());

        //Set date of when post was created
        TextView postDate = (TextView) findViewById(R.id.post_date);
        postDate.setText(AndroidUtils.convertDate(post.getTimeStamp()));
    }

    public String getIntentString(String value){
        Bundle extras = getIntent().getExtras();
        String result = "";
        if (extras != null) {
            result = extras.getString(value);
        }
        return result;
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state
        savedInstanceState.putString("postId", postId);
        savedInstanceState.putString("tab", tab);
        savedInstanceState.putString("userId", userId);
        savedInstanceState.putString("name", name);
        savedInstanceState.putString("posterUserId", posterUserId);
        savedInstanceState.putString("posterName", posterName);
        savedInstanceState.putString("postTimeStamp", postTimeStamp);
        savedInstanceState.putString("postStatus", postStatus);
        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }

    private void setupActivity(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            // Restore value of members from saved state
            if(savedInstanceState.containsKey("tab")) {
                tab = savedInstanceState.getString("tab");
            }
            if(savedInstanceState.containsKey("postId")) {
                postId = savedInstanceState.getString("postId");
            }
            if(savedInstanceState.containsKey("userId")) {
                userId = savedInstanceState.getString("userId");
            }
            if(savedInstanceState.containsKey("name")) {
                name = savedInstanceState.getString("name");
            }
            if(savedInstanceState.containsKey("posterUserId")) {
                posterUserId = savedInstanceState.getString("posterUserId");
            }
            if(savedInstanceState.containsKey("posterName")) {
                posterName = savedInstanceState.getString("posterName");
            }
            if(savedInstanceState.containsKey("postTimeStamp")) {
                postTimeStamp = savedInstanceState.getString("postTimeStamp");
            }
            if(savedInstanceState.containsKey("postStatus")) {
                postStatus = savedInstanceState.getString("postStatus");
            }
        } else {
            postId = getIntentString("postId");
            tab = getIntentString("tab");
            userId = getIntentString("userId");
            posterUserId = getIntentString("posterUserId");
            posterName = getIntentString("posterName");
            postTimeStamp = getIntentString("postTimeStamp");
            postStatus = getIntentString("postStatus");
            // Probably initialize members with default values for a new instance
        }

        databaseQuery = new DatabaseQuery(this);
        application = ((FireBaseApplication) getApplication());
        progressOverlay = findViewById(R.id.progress_overlay);
        if(application.getName() != null && application.getName() != "") {
            name = application.getName();
        } else {
            if(savedInstanceState != null) {
                if(savedInstanceState.containsKey("name")) {
                    name = savedInstanceState.getString("name");
                }
            }
        }
        toolbar = (Toolbar) findViewById(R.id.comments_appbar);
        notificationManager = (NotificationManager)
                getSystemService(NOTIFICATION_SERVICE);
        commentsView = (RecyclerView) findViewById(R.id.view_comments);
        noCommentsView = (TextView) findViewById(R.id.no_comments_text);
        llm = new LinearLayoutManager(this);
        commentsView.setLayoutManager(llm);
    }
}

AndroidManifest.xml:

    <activity
        android:name=".com.tabs.activity.Comments"
        android:label="View Post"
        android:configChanges="orientation|keyboardHidden"
        android:windowSoftInputMode="stateAlwaysHidden|adjustPan"
        android:theme="@style/AppTheme.NoActionBar" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".com.tabs.activity.Comments"
            android:configChanges="orientation|keyboardHidden" />

    </activity>

我尝试将我的 TextView 设置为 android:gravity="center_horizo​​ntal|center_vertical" 或尝试设置 android:centerVertical="true" 但前者产生完全相同的行为,后者使我的 TextView 甚至不显示。有什么方法可以修复 TextView 的位置吗?任何帮助将不胜感激,谢谢!

最佳答案

在Manifest.xml的activity标签中添加android:windowSoftInputMode="adjustPan"

关于java - 如何在RelativeLayout中固定Textview的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36857984/

相关文章:

Java - 分解代码

java - java 获取二维数组中行和列的最大长度

android - 我创建了一个登录页面。如何将这些登录参数发送到服务器进行验证并取回结果?

android - 我可以为现有应用程序添加新的 AdWhirl 广告网络吗?

java - 单击按钮时将项目添加到 RecyclerView

android - 包括标签和数据绑定(bind)

android - 防止 ImageView 将 View 推离屏幕

Java 遵循的路径

java - 更改“确定”按钮的标题 JOptionPane.showConfirmDialog

android - PhoneGap - 防止屏幕方向改变