Textview Gravity在android中无法正常工作

时间:2013-09-26 10:07:47

标签: java android layout-gravity

我的代码出了什么问题,我试图在不同的位置(左,右,中)显示名为"invalid"的TextView,但重力(左,右,中)不起作用! enter image description here

我的text.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp" >

    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/etext"
        android:hint="@string/comment"
        android:inputType="textPassword"/>

    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="100">
        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/button" 
            android:layout_weight="25"/>

        <ToggleButton
            android:id="@+id/toggleButton1"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:text="ToggleButton" 
            android:layout_weight="75"
            android:checked="true"
            android:paddingLeft="15dp"/>
    </LinearLayout>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/invalid"
        android:layout_gravity="center"
        android:gravity="center" />
</LinearLayout>

我的TextPlay.java

public class TextPlay extends Activity {
    Button button;
    ToggleButton tbutton;
    TextView tview;
    EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text);
        button = (Button) findViewById(R.id.button1);
        tbutton = (ToggleButton) findViewById(R.id.toggleButton1);
        tview = (TextView) findViewById(R.id.textView1);
        et = (EditText) findViewById(R.id.etext);
        tbutton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (tbutton.isChecked()) {
                    et.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {
                    et.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String input = et.getText().toString();
                System.out.println(input);
                if (input.contentEquals("left")) {
                    tview.setGravity(Gravity.LEFT);
                } else if (input.contentEquals("right")) {
                    System.out.println("inside right");
                    tview.setGravity(Gravity.RIGHT);
                } else if (input.contentEquals("right")) {
                    tview.setGravity(Gravity.CENTER);
                }
            }
        });
    }
}

5 个答案:

答案 0 :(得分:29)

99%的时间,not working properly == not used properly

您误以为gravitylayout_gravity

gravity是文本在TextView 中与对齐的方式。 TextView中的wrap_content无效,因为TextView与文字大小完全相同。

layout_gravityTextView在其父级中对齐的方式,在您的情况下是LinearLayout

答案 1 :(得分:24)

您将此文本视图设置为“ wrap_content ”的宽度,这意味着,无论文本是什么,视图都会占用文本的大小。

LinearLayout中,默认引力(此处使用)为“中心

你应该试试这个:

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"   <= change this
android:layout_height="wrap_content"
android:text="@string/invalid"
android:gravity="center"   <= then this gravity will be taken into account
/>

答案 2 :(得分:2)

您已经给出了TextView宽度wrap_content,这就是问题,请检查以下代码并将其替换为您的代码。

<TextView
android:id="@+id/txtInvalid"
android:layout_width="match_parent"   
android:layout_height="wrap_content"
android:text="@string/invalid"
android:gravity="center"   
/>

答案 3 :(得分:0)

为textView1

设置android:layout_width="fill_parent"

答案 4 :(得分:0)

确保你没有那样的东西挂在

class TaskDataSource: NSObject, UICollectionViewDataSource {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return TaskDataSource.Sections.count
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count: Int
        switch TaskDataSource.Sections[section] {
        case .Meals:
            count = mealsResultsController?.sections?.first?.numberOfObjects ?? 0
        case .Exercise:
            count = exerciseResultsController?.sections?.first?.numberOfObjects ?? 0
        case .Health:
            count = healthResultsController?.sections?.first?.numberOfObjects ?? 0
        case .Training:
            count = trainingResultsController?.sections?.first?.numberOfObjects ?? 0
        case .Misc:
            count = miscResultsController?.sections?.first?.numberOfObjects ?? 0
        }

        return count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let task: Task
        // Each fetched results controller has a singel section, so we have to make an appropriate index path
        let adjustedIndexPath = NSIndexPath(forItem: indexPath.item, inSection: 0)
        switch TaskDataSource.Sections[indexPath.section] {
        case .Meals:
            task = mealsResultsController?.objectAtIndexPath(adjustedIndexPath) as! Task
        case .Exercise:
            task = exerciseResultsController?.objectAtIndexPath(adjustedIndexPath) as! Task
        case .Health:
            task = healthResultsController?.objectAtIndexPath(adjustedIndexPath) as! Task
        case .Training:
            task = trainingResultsController?.objectAtIndexPath(adjustedIndexPath) as! Task
        case .Misc:
            task = miscResultsController?.objectAtIndexPath(adjustedIndexPath) as! Task
        }

        // This part will vary, depending on your cell / storyboard, but this is the idea.  Note we don't use the adjusted index path here
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("TaskCell", forIndexPath: indexPath) as! TaskCell
        cell.titleLabel.text = task.title

        return cell
    }

    init(dog: Dog) {
        // Create a sort descriptor to sort by whatever you like, I assume you'd want things sorted by title
        let sortDescriptor = NSSortDescriptor(key: "title", ascending: true)

        // A closure to create an NSFetchedResultsController, this avoids copy/pasting
        let createFetchRequestForType = { (type: Type) -> NSFetchedResultsController? in
            let fetchRequest = NSFetchRequest(entityName: Task.kClassName)
            // Note, you'll want to create a multi-key index on the Task entity to make sure this is reasonably fast
            fetchRequest.predicate = NSPredicate(format: "dog == %@ && type == %@", dog, type.rawValue)
            fetchRequest.sortDescriptors = [sortDescriptor]

            let context = Stack.sharedStack.managedObjectContext
            let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
            do {
                try fetchedResultsController.performFetch()
            }
            catch {
                return nil
            }

            return fetchedResultsController
        }

        mealsResultsController = createFetchRequestForType(.Meals)
        exerciseResultsController = createFetchRequestForType(.Exercise)
        healthResultsController = createFetchRequestForType(.Health)
        trainingResultsController = createFetchRequestForType(.Training)
        miscResultsController = createFetchRequestForType(.Misc)
    }

    static let Sections: Array<Type> = [.Meals, .Exercise, .Health, .Training, .Misc]

    var mealsResultsController: NSFetchedResultsController?
    var exerciseResultsController: NSFetchedResultsController?
    var healthResultsController: NSFetchedResultsController?
    var trainingResultsController: NSFetchedResultsController?
    var miscResultsController: NSFetchedResultsController?
}